import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Card, Divider} from 'antd'
import {searchUserRolesByUsernameOrEmail, updateRoleChange} from '../../../action/user'
import UserAssignRolesBox from './user-assign-roles-box'
import {FormattedMessage} from 'react-intl'

class RolesManagementBodyPage extends Component {
  state = {
    usernameOrEmails: [],
    operateType: 'refresh'
  }

  componentDidMount() {
    const {user} = this.props
    this.getAllRoleUsers(user.currentOrganizationId)
  }

  getAllRoleUsers(currentOrganizationId) {
    this.props.getRoleUsers([], currentOrganizationId)
  }

  handleUsernameOrEmailChange(e) {
    let usernameOrEmails = e.target.value
    this.setState({usernameOrEmails})
  }

  convertUsernameOrEmailsToList() {
    let {usernameOrEmails} = this.state
    return usernameOrEmails.split("\n")
      .map(val => val.trim())
      .filter(val => val.length > 0)

  }

  handleSearchClick() {
    const {user} = this.props
    const usernameOrEmails = this.convertUsernameOrEmailsToList()
    this.setState({operateType: 'search'}, () => {
      this.props.getRoleUsers(usernameOrEmails, user.currentOrganizationId)
    })

  }

  handleRoleChange(e) {
    const {user} = this.props
    const {value, checked} = e.target
    const userId = value.split(',')[0]
    const roleNumber = value.split(',')[1]
    const type = checked ? 'ADD' : 'DELETE'
    const usernameOrEmails = this.state.operateType === 'refresh'
      ?
      []
      : this.convertUsernameOrEmailsToList()

    this.props.updateRoleChange(userId, roleNumber, type, usernameOrEmails, user.currentOrganizationId)
  }

  handleRefreshClick() {
    const {user} = this.props
    this.setState({operateType: 'refresh'}, () => {
      this.getAllRoleUsers(user.currentOrganizationId)
    })

  }

  render() {
    const {usersRole} = this.props

    return (
      <Card title={<FormattedMessage id='角色管理'/>}>
        <UserAssignRolesBox
          usersRole={usersRole}
          usernameOrEmails={this.state.usernameOrEmails}
          getRoleUser={this.props.getRoleUsers}
          handleUsernameOrEmailChange={this.handleUsernameOrEmailChange.bind(this)}
          handleSearchClick={this.handleSearchClick.bind(this)}
          handleRefreshClick={this.handleRefreshClick.bind(this)}
          handleRoleChange={this.handleRoleChange.bind(this)}/>
        <Divider dashed/>
      </Card>
    )
  }
}

const mapStateToProps = ({usersRole, user}) => ({
  usersRole,
  user
})

const mapDispatchToProps = dispatch => ({
  getRoleUsers: (usernameOrEmails, currentOrganizationId) => dispatch(searchUserRolesByUsernameOrEmail(usernameOrEmails, currentOrganizationId)),
  updateRoleChange: (userId, roleNumber, type, usernameOrEmails,currentOrganizationId) => dispatch(updateRoleChange(userId, roleNumber, type, usernameOrEmails, currentOrganizationId))
})

export default connect(mapStateToProps, mapDispatchToProps)(RolesManagementBodyPage)